/**
 * 项目管理相关API接口
 */
import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import type { ProjectStatus } from '@/types/project'

// 项目状态通过状态管理系统动态获取
// 使用 useProjectStates() composable 获取动态状态选项

// 项目优先级枚举
export enum ProjectPriority {
  LOW = 'low',          // 低
  MEDIUM = 'medium',    // 中
  HIGH = 'high',        // 高
  CRITICAL = 'critical' // 严重
}

// 项目类型枚举
export enum ProjectType {
  WEB = 'web',                    // Web应用
  MOBILE = 'mobile',              // 移动应用
  DESKTOP = 'desktop',            // 桌面应用
  API = 'api',                    // API服务
  INFRASTRUCTURE = 'infrastructure', // 基础设施
  RESEARCH = 'research',          // 研究项目
  MAINTENANCE = 'maintenance',    // 维护项目
  OTHER = 'other'                 // 其他
}

// 项目成员角色枚举
export enum ProjectRole {
  OWNER = 'owner',           // 项目所有者
  MANAGER = 'manager',       // 项目经理
  DEVELOPER = 'developer',   // 开发者
  TESTER = 'tester',        // 测试员
  DESIGNER = 'designer',     // 设计师
  ANALYST = 'analyst',       // 分析师
  VIEWER = 'viewer'          // 查看者
}

// 项目成员接口（与 types/project.ts 保持一致）
export interface ProjectMember {
  user_id: string
  role?: ProjectRole // 保留用于向后兼容
  roles?: string[] // 项目角色ID列表（新字段）
  joined_at: string
  permissions: string[] // 权限列表
  // 用户信息（从后端返回时可能包含）
  name?: string
  user_name?: string
  username?: string
  email?: string
  user_email?: string
  avatar?: string
  user_avatar?: string // 向后兼容
  id?: string // 向后兼容
  is_active?: boolean // 向后兼容
}

// 项目基础接口
export interface ProjectBase {
  name: string
  description?: string
  project_type: ProjectType
  status: ProjectStatus
  priority: ProjectPriority
  start_date?: string
  end_date?: string
  budget?: number
  tags: string[]
  is_public: boolean
  repository_url?: string
  documentation_url?: string
}

// 项目创建接口
export interface ProjectCreate extends ProjectBase {}

// 项目更新接口
export interface ProjectUpdate {
  name?: string
  description?: string
  project_type?: ProjectType
  status?: ProjectStatus
  priority?: ProjectPriority
  start_date?: string
  end_date?: string
  budget?: number
  tags?: string[]
  is_public?: boolean
  repository_url?: string
  documentation_url?: string
  owner_id?: string
}

// 项目响应接口
export interface ProjectResponse {
  id: string
  name: string
  description?: string
  project_type: ProjectType
  status: ProjectStatus
  priority: ProjectPriority
  start_date?: string
  end_date?: string
  budget?: number
  tags: string[]
  is_public: boolean
  repository_url?: string
  documentation_url?: string
  created_by: string
  created_by_name?: string
  created_at: string
  updated_at: string
  is_archived: boolean
  archived_at?: string
  members: ProjectMember[]
  owner_id?: string
  member_count: number
  task_count: number
  completed_task_count: number
  requirement_count: number
  requirement_completed_count?: number // 已完成需求数量（可选，某些API可能不返回）
  test_case_count: number
  passed_test_case_count?: number // 已通过测试用例数量（可选，某些API可能不返回）
  defect_count: number
  resolved_defect_count?: number // 已解决缺陷数量（可选，某些API可能不返回）
  progress: number
  is_overdue: boolean
  days_remaining?: number
  is_pinned?: boolean // 是否置顶（可选）
}

// 项目统计接口
export interface ProjectStats {
  total_projects: number
  active_projects: number
  completed_projects: number
  overdue_projects: number
  projects_by_status: Record<string, number>
  projects_by_priority: Record<string, number>
  projects_by_category: Record<string, number>
}

// 项目筛选接口
export interface ProjectFilter {
  status?: ProjectStatus[]
  priority?: ProjectPriority[]
  project_type?: ProjectType[]
  created_by?: string
  member_id?: string
  is_archived?: boolean
  start_date_from?: string
  start_date_to?: string
  end_date_from?: string
  end_date_to?: string
  tags?: string[]
}

// 获取项目列表
export function getProjects(params?: {
  page?: number
  size?: number
  search?: string
  status?: string
  priority?: string
  project_type?: string
  created_by?: string
  member_id?: string
  is_archived?: boolean
}): Promise<ApiResponse<{
  data: ProjectResponse[]
  pagination: {
    page: number
    size: number
    total: number
    pages: number
  }
}>> {
  // 过滤空参数
  const requestParams: any = {}
  if (params) {
    if (params.page !== undefined) requestParams.page = params.page
    if (params.size !== undefined) requestParams.size = params.size
    if (params.search && params.search.trim()) requestParams.search = params.search
    if (params.status && params.status.trim()) requestParams.status = params.status
    if (params.priority && params.priority.trim()) requestParams.priority = params.priority
    if (params.project_type && params.project_type.trim()) requestParams.project_type = params.project_type
    if (params.created_by && params.created_by.trim()) requestParams.created_by = params.created_by
    if (params.member_id && params.member_id.trim()) requestParams.member_id = params.member_id
    if (params.is_archived !== undefined) requestParams.is_archived = params.is_archived
  }

  return request<ApiResponse<{
    data: ProjectResponse[]
    pagination: {
      page: number
      size: number
      total: number
      pages: number
    }
  }>>({
    url: '/projects/',
    method: 'get',
    params: requestParams
  }).then(response => response.data)
}

// 获取单个项目
export function getProject(id: string): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/${id}`,
    method: 'get'
  }).then(response => response.data)
}

// 获取项目详情（getProject 的别名，用于向后兼容）
export function getProjectDetail(id: string): Promise<ApiResponse<ProjectResponse>> {
  return getProject(id)
}

// 获取项目活动记录
export function getProjectActivities(id: string, params?: {
  page?: number
  size?: number
}): Promise<ApiResponse<{
  items: any[]
  total: number
  page: number
  size: number
}>> {
  // 转换分页参数
  const requestParams: any = {}
  
  if (params) {
    if (params.page !== undefined && params.size !== undefined) {
      requestParams.skip = (params.page - 1) * params.size
      requestParams.limit = params.size
    }
  }
  
  return request<ApiResponse<{
    items: any[]
    total: number
    page: number
    size: number
  }>>({
    url: `/projects/${id}/activities`,
    method: 'get',
    params: requestParams
  }).then(response => response.data)
}

// 创建项目
export function createProject(data: ProjectCreate): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: '/projects/',
    method: 'post',
    data
  }).then(response => response.data)
}

// 更新项目
export function updateProject(id: string, data: ProjectUpdate): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/${id}`,
    method: 'put',
    data
  }).then(response => response.data)
}

// 删除项目
export function deleteProject(id: string): Promise<ApiResponse<void>> {
  return request<ApiResponse<void>>({
    url: `/projects/${id}`,
    method: 'delete'
  }).then(response => response.data)
}

// 归档项目
export function archiveProject(id: string): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/${id}/archive`,
    method: 'post'
  }).then(response => response.data)
}

// 取消归档项目
export function unarchiveProject(id: string): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/${id}/unarchive`,
    method: 'post'
  }).then(response => response.data)
}

// 恢复项目（取消归档的别名）
export function restoreProject(id: string): Promise<ApiResponse<ProjectResponse>> {
  return unarchiveProject(id)
}

// 获取项目成员
export function getProjectMembers(id: string): Promise<ApiResponse<ProjectMember[]>> {
  return request<ApiResponse<ProjectMember[]>>({
    url: `/projects/${id}/members`,
    method: 'get'
  }).then(response => response.data)
}

// 添加项目成员
export function addProjectMember(id: string, data: {
  user_id: string
  roles: string[] // 项目角色ID列表
  permissions?: string[]
}): Promise<ApiResponse<ProjectMember>> {
  return request<ApiResponse<ProjectMember>>({
    url: `/projects/${id}/members`,
    method: 'post',
    data
  }).then(response => response.data)
}

// 移除项目成员
export function removeProjectMember(id: string, userId: string): Promise<ApiResponse<void>> {
  return request<ApiResponse<void>>({
    url: `/projects/${id}/members/${userId}`,
    method: 'delete'
  }).then(response => response.data)
}

// 更新项目成员角色
export function updateProjectMemberRole(id: string, userId: string, role: ProjectRole): Promise<ApiResponse<ProjectMember>> {
  return request<ApiResponse<ProjectMember>>({
    url: `/projects/${id}/members/${userId}`,
    method: 'put',
    data: { role }
  }).then(response => response.data)
}

// 更新项目成员信息
export function updateProjectMember(id: string, userId: string, data: {
  roles?: string[] // 项目角色ID列表
  permissions?: string[]
}): Promise<ApiResponse<ProjectMember>> {
  return request<ApiResponse<ProjectMember>>({
    url: `/projects/${id}/members/${userId}`,
    method: 'put',
    data
  }).then(response => response.data)
}

// 获取项目统计信息
export function getProjectStats(): Promise<ApiResponse<ProjectStats>> {
  return request<ApiResponse<ProjectStats>>({
    url: '/projects/stats/overview',
    method: 'get'
  }).then(response => response.data)
}

// 获取用户参与的项目
export function getUserProjects(userId?: string): Promise<ApiResponse<ProjectResponse[]>> {
  return request<ApiResponse<ProjectResponse[]>>({
    url: '/projects/user',
    method: 'get',
    params: userId ? { user_id: userId } : undefined
  }).then(response => response.data)
}

// 搜索项目
export function searchProjects(query: string): Promise<ApiResponse<ProjectResponse[]>> {
  return request<ApiResponse<ProjectResponse[]>>({
    url: '/projects/search',
    method: 'get',
    params: { q: query }
  }).then(response => response.data)
}

// 获取项目模板
export function getProjectTemplates(): Promise<ApiResponse<{
  id: string
  name: string
  description: string
  project_type: ProjectType
  default_settings: Partial<ProjectBase>
}[]>> {
  return request<ApiResponse<{
    id: string
    name: string
    description: string
    project_type: ProjectType
    default_settings: Partial<ProjectBase>
  }[]>>({
    url: '/projects/templates',
    method: 'get'
  }).then(response => response.data)
}

// 从模板创建项目
export function createProjectFromTemplate(templateId: string, data: Partial<ProjectCreate>): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/templates/${templateId}/create`,
    method: 'post',
    data
  }).then(response => response.data)
}

// 导出项目数据
export function exportProject(id: string, format: 'json' | 'csv' | 'excel' = 'json'): Promise<Blob> {
  return request({
    url: `/projects/${id}/export`,
    method: 'get',
    params: { format },
    responseType: 'blob'
  })
}

// 复制项目
export function duplicateProject(id: string, data: {
  name: string
  include_members?: boolean
  include_tasks?: boolean
  include_requirements?: boolean
}): Promise<ApiResponse<ProjectResponse>> {
  return request<ApiResponse<ProjectResponse>>({
    url: `/projects/${id}/duplicate`,
    method: 'post',
    data
  }).then(response => response.data)
}

// 为了向后兼容，创建 projectAPI 对象（使用函数而不是类）
export const projectAPI = {
  getProjects,
  getProject,
  createProject,
  updateProject,
  deleteProject,
  archiveProject,
  unarchiveProject,
  restoreProject,
  getProjectMembers,
  addProjectMember,
  removeProjectMember,
  updateProjectMemberRole,
  getProjectStats,
  getUserProjects,
  searchProjects,
  getProjectTemplates,
  createProjectFromTemplate,
  exportProject,
  duplicateProject,
  getProjectActivities
}

// 默认导出
export default projectAPI

// 为了兼容性，添加 getProjectList 函数，返回 {items: [...], total: number} 格式
export function getProjectList(params?: {
  page?: number
  size?: number
  search?: string
  status?: string
  priority?: string
  project_type?: string
  created_by?: string
  member_id?: string
  is_archived?: boolean
}): Promise<{
  items: ProjectResponse[]
  total: number
  page: number
  size: number
}> {
  // 转换参数格式，过滤空值
  const convertedParams: any = {}
  if (params) {
    if (params.page !== undefined) convertedParams.page = params.page
    if (params.size !== undefined) {
      const sanitizedSize = Number(params.size)
      if (!Number.isNaN(sanitizedSize)) {
        convertedParams.size = Math.min(Math.max(sanitizedSize, 1), 100)
      }
    }
    if (params.search && params.search.trim()) convertedParams.search = params.search
    if (params.status && params.status.trim()) convertedParams.status = params.status
    if (params.priority && params.priority.trim()) convertedParams.priority = params.priority
    if (params.project_type && params.project_type.trim()) convertedParams.project_type = params.project_type
    if (params.created_by && params.created_by.trim()) convertedParams.created_by = params.created_by
    if (params.member_id && params.member_id.trim()) convertedParams.member_id = params.member_id
    if (params.is_archived !== undefined) convertedParams.is_archived = params.is_archived
  }

  return request({
    url: '/projects/',
    method: 'get',
    params: convertedParams
  }).then(response => {
    // 根据后端实际响应格式处理数据
    // 后端返回格式: {success: true, code: 200, message: "获取成功", data: [...], pagination: {...}}
    const responseData = response.data
    
    // 处理统一API响应格式
    let data: any
    let pagination: any = {}
    
    if (responseData && typeof responseData === 'object') {
      // 如果是标准API响应格式 {success: true, data: [...], pagination: {...}}
      if (responseData.success && responseData.data) {
        data = responseData.data
        pagination = responseData.pagination || {}
      } else if (Array.isArray(responseData.data)) {
        // 直接是 {data: [...], pagination: {...}} 格式
        data = responseData.data
        pagination = responseData.pagination || {}
      } else if (Array.isArray(responseData)) {
        // 直接是数组格式
        data = responseData
      } else {
        // 其他格式，尝试提取数据
        data = responseData.data || responseData.items || []
        pagination = responseData.pagination || {}
      }
    } else {
      data = []
    }
    
    // 提取项目数据和分页信息
    const items = Array.isArray(data) ? data : (Array.isArray(data?.items) ? data.items : [])
    const total = pagination.total || data?.total || items.length
    const page = pagination.page || params?.page || 1
    const size = pagination.size || params?.size || 10
    
    return {
      items: items as ProjectResponse[],
      total,
      page,
      size
    }
  })
}

export function getProjectDashboardStats(params?: {
  start_date?: string
  end_date?: string
  period?: 'week' | 'month' | 'quarter'
}): Promise<ApiResponse<{
  progress_distribution: Array<{ value: number; name: string }>
  status_distribution: Array<{ value: number; name: string; code: string }>
  trend_data: {
    labels: string[]
    created: number[]
    completed: number[]
  }
  team_efficiency: Array<{
    user_id: string
    name: string
    completed_count: number
    total_count: number
  }>
}>> {
  return request<ApiResponse<{
    progress_distribution: Array<{ value: number; name: string }>
    status_distribution: Array<{ value: number; name: string; code: string }>
    trend_data: {
      labels: string[]
      created: number[]
      completed: number[]
    }
    team_efficiency: Array<{
      user_id: string
      name: string
      completed_count: number
      total_count: number
    }>
  }>>({
    url: '/projects/stats/dashboard',
    method: 'get',
    params,
    timeout: 30000 // 增加超时时间到30秒
  }).then(response => {
    // 返回完整的API响应对象，而不是response.data
    // 这样调用方可以检查response.success和response.data
    return response.data
  })
}

// 置顶项目
export function pinProject(id: string): Promise<ApiResponse<void>> {
  return request<ApiResponse<void>>({
    url: `/projects/${id}/pin`,
    method: 'post'
  }).then(response => response.data)
}

// 取消置顶项目
export function unpinProject(id: string): Promise<ApiResponse<void>> {
  return request<ApiResponse<void>>({
    url: `/projects/${id}/pin`,
    method: 'delete'
  }).then(response => response.data)
}

// 为了兼容性，导出Project类型别名
export type Project = ProjectResponse